package com.yonyou.brigade.third_parties.fanscar.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.fanscar.dao.FanscarUserMapper;
import com.yonyou.brigade.third_parties.fanscar.model.FanscarConfig;
import com.yonyou.brigade.third_parties.fanscar.model.FanscarUser;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarDocService;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarPublicService;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarUserService;
import com.yonyou.brigade.third_parties.fanscar.util.JobGradeConvertUtil;
import com.yonyou.brigade.third_parties.fanscar.util.UserConvertUtil;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 单点登录及用户服务
 *
 * @author kangfw5
 * @since : 2019-03-01
 */
@Service
public class FanscarUserServiceImpl extends ServiceImpl<FanscarUserMapper, FanscarUser> implements IFanscarUserService {
    private final static Logger logger = LoggerFactory.getLogger(FanscarUserServiceImpl.class);

    private final String COMPARE_PROPERTIES = "employeeId,employeeName,employeeNumber,departmentCode,jobGradeCode,gender,mobile,status";

    @Value("${fanscar.login.flight}")
    private String FANSCAR_LOGIN_FLIGHT;

    @Value("${fanscar.login.train}")
    private String FANSCAR_LOGIN_TRAIN;

    @Value("${fanscar.login.hotel}")
    private String FANSCAR_LOGIN_HOTEL;

    @Value("${fanscar.login.car}")
    private String FANSCAR_LOGIN_CAR;

    @Value("${brigade.url.noaccess}")
    private String BRIGADE_NOACCESS_URL;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("fanscarPublicServiceImpl")
    private IFanscarPublicService fanscarPublicService;

    @Autowired
    @Qualifier("fanscarDocServiceImpl")
    private IFanscarDocService fanscarDocService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    private FanscarUserMapper fanscarUserMapper;

    @Autowired
    @Qualifier("baseDocServiceImpl")
    private IBaseDocService baseDocService;

    /**
     * 获取登录地址URL
     *
     * @param tenant   租户ID
     * @param org      组织PK
     * @param phone    用户手机号
     * @param pageType 跳转页面
     * @param pcOrH5   PC还是H5跳转（目前只支持H5）
     * @param jsonExt  其他信息
     * @return String H5跳转URL
     * @since : 2019-03-06
     */
    @Override
    public String getLoginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt) {
        FanscarConfig fanscarConfig = (FanscarConfig) briChannelService.getChannelConfig(tenant, ChannelEnum.FANSCAR.getName(), org, new FanscarConfig());
        if (fanscarConfig == null) {
            return BRIGADE_NOACCESS_URL;
        } else {
            BriChannel briChannel = briChannelService.getEnableChannelByOpenType(tenant, ChannelEnum.FANSCAR.getName(), 2);
            Wrapper<FanscarUser> fanscarUserWrapper = new EntityWrapper<>();
            fanscarUserWrapper.eq("mobile", phone);
            List<FanscarUser> fanscarUsers = fanscarUserMapper.selectList(fanscarUserWrapper);
            UcUserDto ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
            if (ucUserDto == null) {
                throw new CustomException("用户信息不存在或未进入用户中心");
            }
            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                // 如果用户没有通步过则同步用户
                FanscarUser fanscarUser = UserConvertUtil.convertToFanscarUser(ucUserDto);
                if (CollectionUtils.isEmpty(fanscarUsers)) {
                    List<FanscarUser> employeeList = new ArrayList<>();
                    employeeList.add(fanscarUser);
                    JSONArray employeeResult = fanscarDocService.createEmployee(employeeList, fanscarConfig);
                    if (CollectionUtils.isEmpty(employeeResult)) {
                        fanscarUserMapper.insert(fanscarUser);
                    }
                } else {
                    Map<String, String> compareMap = new HashMap<>();
                    String[] compareFields = COMPARE_PROPERTIES.split(",");
                    if (compareFields.length > 0) {
                        for (int i = 0; i < compareFields.length; i++) {
                            //此处只需要key值
                            compareMap.put(compareFields[i], "");
                        }
                    }
                    Map<String, Object> compareResult = CompareUtils.getModifyContent(fanscarUsers.get(0), fanscarUser, compareMap);
                    if (compareResult != null && compareResult.size() > 0) {
                        List<FanscarUser> employeeList = new ArrayList<>();
                        employeeList.add(fanscarUser);
                        JSONArray employeeResult = fanscarDocService.updateEmployee(employeeList, fanscarConfig);
                        if (CollectionUtils.isEmpty(employeeResult)) {
                            fanscarUser.setId(fanscarUsers.get(0).getId());
                            fanscarUserMapper.updateById(fanscarUser);
                        }

                        //TODO 部门发生变更无需处理 职级发生变更需要重新同步职级
                        if (BriChannel.SYNCRANK == briChannel.getSyncRank()) {
                            if (compareResult.containsKey("jobGradeCode")) {
                                List<Map<String, String>> dutyList = baseDocService.getDutyByTenantAndOrg(tenant, org);
                                fanscarDocService.createJobGrade(JobGradeConvertUtil.convertToFanscarJobGradeList(dutyList), fanscarConfig);
                                fanscarDocService.updateJobGrade(JobGradeConvertUtil.convertToFanscarJobGradeList(dutyList), fanscarConfig);
                            }
                        }
                    }
                }
            }
            String h5Token = fanscarPublicService.getH5Token(ucUserDto.getPersonCode(), fanscarConfig);
            if (pageType == null) {
                return FANSCAR_LOGIN_FLIGHT + "?token=" + h5Token;
            }
            switch (pageType) {
                case "flight":
                    return FANSCAR_LOGIN_FLIGHT + "?token=" + h5Token;
                case "hotel":
                    return FANSCAR_LOGIN_HOTEL + "?token=" + h5Token;
                case "train":
                    return FANSCAR_LOGIN_TRAIN + "?token=" + h5Token;
                case "car":
                    return FANSCAR_LOGIN_CAR + "?token=" + h5Token;
                default:
                    return FANSCAR_LOGIN_FLIGHT + "?token=" + h5Token;
            }
        }
    }

    /**
     * 创建或更新员工信息
     *
     * @param employee      员工信息
     * @param fanscarConfig 认证配置信息
     * @since : 2019-03-05
     */
    @Override
    public void insertOrUpdateEmployee(FanscarUser employee, FanscarConfig fanscarConfig) {
        Wrapper<FanscarUser> wrapper = new EntityWrapper<>();
        wrapper.eq(FanscarUser.EMPLOYEE_ID, employee.getEmployeeId());
        List<FanscarUser> fanscarUserList = selectList(wrapper);
        if (CollectionUtils.isEmpty(fanscarUserList)) {
            fanscarDocService.createEmployee(Collections.singletonList(employee), fanscarConfig);
            fanscarUserMapper.insert(employee);
        } else {
            Map<String, String> compareMap = new HashMap<>();
            String[] compareFields = COMPARE_PROPERTIES.split(",");
            if (compareFields.length > 0) {
                for (int i = 0; i < compareFields.length; i++) {
                    compareMap.put(compareFields[i], "");
                }
            }
            Map<String, Object> compareResult = CompareUtils.getModifyContent(fanscarUserList.get(0), employee, compareMap);
            if (compareResult != null && compareResult.size() > 0) {
                fanscarDocService.updateEmployee(Collections.singletonList(employee), fanscarConfig);
                employee.setId(fanscarUserList.get(0).getId());
                fanscarUserMapper.updateById(employee);
            }
        }
    }
}
